﻿using ELF.Core;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;


namespace ELF.Modules;
public static class ModuleLoader
{
    public static async Task LoadAsync(this IHostApplicationBuilder builder, params Type[] startupModuleTypes)
    {
        var services = builder.Services;
        var allSortedModules = new List<Type>();

        foreach (var startupModule in startupModuleTypes)
        {
            var sortedModules = ModuleSortedHelper.GetSortedModules(startupModule);
            allSortedModules.AddRange(sortedModules);
        }

        // 去重并保持顺序
        var distinctSortedModules = allSortedModules
            .Distinct()
            .ToList();

        // 创建实例并配置服务
        var moduleInstances = distinctSortedModules
            .Select(Activator.CreateInstance)
            .Cast<IModule>()
            .ToList();

        foreach (var module in moduleInstances)
        {
            await module.ConfigureServicesAsync(builder);

            ConsoleLog.Info($"Module {module.GetType().Name} configured services.");
        }

        services.AddSingleton(new ModuleCollection(moduleInstances));
    }

    public static async Task InitializeAsync(this IApplicationBuilder app)
    {
        var modules = app.ApplicationServices
            .GetRequiredService<ModuleCollection>()
            .Modules;

        foreach (var module in modules)
        {
            await module.InitializeAsync(app);
            var logger = app.ApplicationServices.GetRequiredService<ILogger<IApplicationBuilder>>();
            ConsoleLog.Info($"Module {module.GetType().Name} initialized.");
        }
    }
}